local addon, ns = ...
local C = ns.shared.color
local L = ns.L
local LDB = LibStub("LibDataBroker-1.1")

local is_init = false

local ADDONNAME = "Broker_Everything"

LibQTip	= LibStub:GetLibrary("LibQTip-1.0")


local tooltip = nil

Broker_Everything = CreateFrame("Frame")
Broker_Everything:RegisterEvent("ADDON_LOADED")

-- config
Broker_EverythingDB = {}
Broker_EverythingGlobalDB = {}

local Print = function (w, x)
	DEFAULT_CHAT_FRAME:AddMessage("|cFFFF0000Broker_Everything:|r|cFF00FF00" .. w .. ":|r " .. x)
end




--
-- update handling
--
local updateTab = {}
local updateFrame = nil
local updateMmpf = 0

local function UpdateHandler(self, elapsed)
	updateMmpf = updateMmpf + elapsed
	if updateMmpf < 1 then
		return
	end

	updateMmpf = 0

	for _, v in pairs(updateTab) do
		v.elapsed = v.elapsed + 1
		if v.elapsed > v.interval then
			v.elapsed = v.elapsed - v.interval
			v.func (v.arg)
		end
	end
end


local function RegisterForUpdates(func, arg, interval)
	func(arg)

	if not updateFrame then
		updateFrame = CreateFrame("Frame")
		updateFrame:SetScript("OnUpdate", UpdateHandler)
	end

	table.insert (updateTab, {
		func = func,
		arg = arg,
		interval = interval,
		elapsed = 0,
	})
end


local modules_init_later = {}
function Broker_Everything:Register(name, icon, init, event, events, click, tooltip, up, upi)
	if not is_init then
		table.insert(modules_init_later, {name, icon, init, event, events, click, tooltip, up, upi})
		return
	end


	if icon == 0 then icon = nil end
	if init == 0 then init = nil end
	if event == 0 then event = nil end
	if events == 0 then events = nil end
	if click == 0 then click = nil end
	if tooltip == 0 then tooltip = nil end

	local ret = {}
	
	if event then
		ret = CreateFrame("Frame")
	end

	local label = nil

	if Broker_EverythingDB.labels == 1 then
		label = "BE: " .. name
	end

	if init then
		init()
	end

	ret.obj = LDB:NewDataObject (name, {
		type = "data source",
		icon = icon,
		iconCoords = {0.05, 0.95, 0.05, 0.95},
		OnClick = click,
		OnTooltipShow = tooltip,
		label = label,
	})

	if event then
		for _, e in pairs(events) do
			ret:RegisterEvent(e)
		end

		ret:SetScript ("OnEvent", event)
		ret.eventfunc = event
	end

	if up then
		RegisterForUpdates(up, ret, upi)
	end

	if init then
		init(ret)
	end
end

--Register the modules into the database for use.
function Broker_Everything:DoRegister()
	for _, v in ipairs(modules_init_later) do
		--local module = v[1]:lower()
		local module = v[1]


		--if not Broker_EverythingDB[module] or  not Broker_EverythingDB[module].enabled then
		if Broker_EverythingDB[module] == nil then
			Broker_EverythingDB[module] = {enabled = true}
		end

		if Broker_EverythingDB[module].enabled == true then
			self:Register(unpack (v))
		end
	end
	modules_init_later = nil
end

function Broker_Everything.resetDefaults()
	Broker_EverythingDB={}
	Broker_EverythingGlobalDB = {}
	Broker_EverythingGlobalDB.global = false

	for _, v in ipairs(modules_init_later) do
		--local module = v[1]:lower()
		local module = v[1]
		if Broker_EverythingDB[module] == nil then

			Broker_EverythingDB[module] = {
				enabled = true,
			}
		end
	end

end


Broker_Everything:SetScript("OnEvent", function (self, e, n)
	if e == "ADDON_LOADED" and n == "Broker_Everything" then
		is_init = true

		if Broker_EverythingDB.reset == true then
			self.resetDefaults()
			Broker_EverythingDB["reset"] = false
			Print(L["Warning:"], L["saved variables have been reset. Sorry for the inconvenience!"])
		end

		if Broker_EverythingGlobalDB.global == true then
			Broker_EverythingDB = Broker_EverythingGlobalDB
		end

		if not Broker_EverythingDB.labels then
			Broker_EverythingDB.labels = false
		end
		
		-- Added by Ekaterina to allow for suffix colouring choice,
		if not (Broker_EverythingDB.suffixColour == true or Broker_EverythingDB.suffixColour == false) then 
			Broker_EverythingDB.suffixColour = true
		end

		self:DoRegister()
		self:UnregisterEvent("ADDON_LOADED")
	end
end)


SlashCmdList["BROKER_EVERYTHING"] = function(cmd)
	local cmd, arg = strsplit(" ", cmd:lower(), 2)



	if cmd == L["labels"] then
		if Broker_EverythingDB.labels == true then
			Broker_EverythingDB.labels = false
			Print("cfg", "Labels disabled after reload.")
		else
			Broker_EverythingDB.labels = true
			Print("cfg", "Labels enabled after reload.")
		end
		return
	end

	if cmd == L["max_addons"] then
		Broker_EverythingDB[L["Memory"]].max_addons = tonumber(arg)
		if Broker_EverythingDB[L["Memory"]].max_addons > 0 then
			Print("cfg", "showing a maximum of " .. Broker_EverythingDB[L["Memory"]].mem_max_addons .. " addons.")
		else
			Print("cfg", "showing all addons.")
		end
		return
	end

	if cmd == L["reset"] then
		Broker_EverythingDB.reset = true
		ReloadUI()
	end

	if cmd == L["global"] then
		if not Broker_EverythingGlobalDB.global or Broker_EverythingGlobalDB.global == false then
			if Broker_EverythingGlobalDB[L["Clock"]] == nil then
				Broker_EverythingGlobalDB = Broker_EverythingDB
			end			
			Broker_EverythingGlobalDB.global = true
		else
			Broker_EverythingGlobalDB.global = false
		end 
		Print(L["Cfg"], L["Broker_Everything will use the new setting on next reload."])
	end

	if cmd == L["list"] then
		Print(L["cfg"], L["Data feeds:"])
		for k, v in pairs(Broker_EverythingDB) do
			if not (v == true or v == false or v == 1 or v == 0) then
				if Broker_EverythingDB[k].enabled == true then
					Print(L["Cfg"],  k .. " (" .. C.dkgreen(L["Enabled"]) .. ")")
				elseif Broker_EverythingDB[k].enabled == false then
					Print(L["Cfg"],  k .. " (" .. C.brtred(L["Disabled"]) .. ")")
				end
			end
		end
		return
	end	
	cmd = cmd:gsub("^%l", string.upper)
	for k, v in pairs(Broker_EverythingDB) do
		if k == cmd then
			local x = Broker_EverythingDB[cmd].enabled
			print(tostring(x))
			if x == true then
				Broker_EverythingDB[cmd].enabled = false
				print(tostring(Broker_EverythingDB[cmd].enabled))
				Print(L["Cfg"], L["Disabling "] .. cmd .. L[" on next reload."])
			else
				Broker_EverythingDB[cmd].enabled = true
				Print(L["Cfg"], L["Enabling "] .. cmd .. L[" on next reload."])
			end
		end
	end
end


SLASH_BROKER_EVERYTHING1 = "/broker_everything"
SLASH_BROKER_EVERYTHING2 = "/be"

